package com.ddc.study.feature.collect.website;

import android.content.DialogInterface;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ddc.study.R;
import com.ddc.study.base.MvpFragment;
import com.ddc.study.entity.CollectWebsite;
import com.ddc.study.feature.html.HtmlActivity;
import com.ddc.study.view.VerticalDecoration;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2018/6/7.
 *
 * @author lshun
 * @version 1.0
 */
public class CollectWebsiteFragment extends MvpFragment<CollectWebsiteContract.IView, CollectWebsiteContract.IPresenter>
        implements CollectWebsiteContract.IView {

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private final Adapter mAdapter = new Adapter();

    public static Fragment getInstance() {
        return new CollectWebsiteFragment();
    }

    @Override
    protected CollectWebsiteContract.IPresenter createPresenter() {
        return new CollectWebsitePresenter();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.frag_collect_website;
    }

    @Override
    protected void initView() {
        super.initView();
        if (getActivity() == null) return;

        mSwipeRefreshLayout.setRefreshing(true);
        mPresenter.loadData();

        mSwipeRefreshLayout.setOnRefreshListener(() -> mPresenter.loadData());

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new VerticalDecoration(getActivity()));

        mAdapter.bindToRecyclerView(mRecyclerView);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            CollectWebsite collectWebsite = mAdapter.getItem(position);
            if (collectWebsite != null && getActivity() != null) {
                HtmlActivity.openUrl(getActivity(), collectWebsite.getLink());
            }
        });

        mAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            final String[] items = {"修改", "删除"};
            final ListPopupWindow listPopupWindow = new ListPopupWindow(getActivity());
            listPopupWindow.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
            listPopupWindow.setOnItemClickListener((parent, view1, pos, id) -> {
                switch (pos) {
                    case 0:
                        showDialog(position);
                        listPopupWindow.dismiss();
                        break;
                    case 1:
                        CollectWebsite item = mAdapter.getItem(position);
                        if (item != null) {
                            mPresenter.deleteLink(item.getId());
                            listPopupWindow.dismiss();
                        }
                        break;
                }
            });
            listPopupWindow.setAnchorView(view);
            listPopupWindow.setHorizontalOffset(view.getWidth() / 2);
            listPopupWindow.setWidth(400);
            listPopupWindow.setModal(false);
            listPopupWindow.show();
            return true;
        });
    }

    @OnClick(R.id.fab)
    void addCollectLink() {
        showDialog(-1);
    }

    /**
     * 新增时{@code position} < 0
     * 修改时{@code position} >= 0
     */
    private void showDialog(final int position) {
        if (getActivity() == null) return;

        //TODO 用DialogFragment替换
        final View v = View.inflate(getActivity(), R.layout.dialog_collect_website, null);

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle(position < 0 ? R.string.add_collect : R.string.edit_collect)
                .setView(v)
                .setCancelable(false)
                .setPositiveButton(android.R.string.ok, null)
                .setNegativeButton(android.R.string.cancel, null)
                .show();

        final EditText edtName = v.findViewById(R.id.edt_name);
        final EditText edtLink = v.findViewById(R.id.edt_link);

        final CollectWebsite item = mAdapter.getItem(position);
        if (item != null) {
            edtName.setText(item.getName());
            edtName.setHint(item.getName());
            edtName.selectAll();
            edtName.requestFocus();
            edtLink.setText(item.getLink());
            edtLink.setHint(item.getLink());
            showSoftInput();
        }

        dialog.getButton(DialogInterface.BUTTON_POSITIVE)
                .setOnClickListener(view -> {
                    boolean valid = true;
                    if (edtLink.getText().length() == 0) {
                        edtLink.setBackgroundResource(R.drawable.edt_background_error);
                        edtLink.requestFocus();
                        valid = false;
                    } else {
                        edtLink.setBackgroundResource(R.drawable.edt_background_normal);
                    }

                    if (edtName.getText().length() == 0) {
                        edtName.setBackgroundResource(R.drawable.edt_background_error);
                        edtName.requestFocus();
                        valid = false;
                    } else {
                        edtName.setBackgroundResource(R.drawable.edt_background_normal);
                    }

                    if (valid) {
                        dialog.dismiss();
                        String name = edtName.getText().toString();
                        String link = edtLink.getText().toString();
                        if (item == null) {
                            mPresenter.collectLink(name, link);
                        } else {
                            mPresenter.editCollectLink(item.getId(), name, link);
                        }
                    }
                });
    }

    @Override
    public void showData(@Nullable List<CollectWebsite> data) {
        if (!mSwipeRefreshLayout.isRefreshing()) return;
        mSwipeRefreshLayout.setRefreshing(false);
        if (data == null) {
            //加载失败
            if (mAdapter.getData().isEmpty()) {
                //recyclerView中无数据展示时提示加载失败
                showToast("加载失败，请重试");
                /*TextView tv = new TextView(getActivity());
                tv.setText("加载失败了，请点击重试...");
                tv.setGravity(Gravity.CENTER);
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mSwipeRefreshLayout.setRefreshing(true);
                        mPresenter.loadData();
                    }
                });
                mAdapter.setEmptyView(tv);*/
            } else {
                //重新加载数据时失败
                showToast("刷新失败，请稍候重试");
            }
        } else {
            //加载成功
            mAdapter.setNewData(data);
        }
    }

    @Override
    public void showAddCollectLinkResult(@Nullable CollectWebsite collectWebsite) {
        if (collectWebsite == null) {
            showToast("新增收藏失败");
        } else {
            mAdapter.addData(collectWebsite);
        }
    }

    @Override
    public void showEditCollectLinkResult(@Nullable CollectWebsite collectWebsite) {
        if (collectWebsite == null) {
            showToast("更新收藏失败");
        } else {
            List<CollectWebsite> data = mAdapter.getData();
            for (int i = 0, len = data.size(); i < len; i++) {
                final CollectWebsite item = data.get(i);
                if (item.getId() == collectWebsite.getId()) {
                    //更新当前数据并通知adapter更新视图
                    item.setName(collectWebsite.getName());
                    item.setLink(collectWebsite.getLink());
                    mAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Override
    public void showDeleteLinkResult(boolean result, int id) {
        if (result) {
            List<CollectWebsite> data = mAdapter.getData();
            for (int i = 0, len = data.size(); i < len; i++) {
                final CollectWebsite item = data.get(i);
                if (item.getId() == id) {
                    //更新当前数据并通知adapter更新视图
                    mAdapter.remove(i);
                    break;
                }
            }
        } else {
            showToast("删除收藏失败");
        }
    }

    private static class Adapter extends BaseQuickAdapter<CollectWebsite, BaseViewHolder> {
        Adapter() {
            super(R.layout.item_collect_website);
        }

        @Override
        protected void convert(BaseViewHolder helper, CollectWebsite item) {
            helper.setText(R.id.tv_title, item.getName());
        }
    }
}
